<?php

class MemberHelper extends Helper {

    private $check_rule;
    private $_field;

    public function __construct() {
        $this->check_rule = array(
            'u_realname' => array('require', '真实姓名不能为空'),
            'u_name' => array('require', '用户名不能为空'),
            'u_mobile' => array('mobile', '手机号错误'),
            'u_scope' => array('require', '权限等级不能为空'),
            'u_role' => array('require', '权限角色不能为空')
        );
        $this->_field = array('u_id', 'u_code', 'u_name', 'u_salt', 'u_password', 'u_role', 'u_realname', 'u_dp_type', 'u_dp_id', 'u_scope', 'u_auditlevel', 'u_mobile', 'u_job', 'u_addr', 'u_idcard', 'u_sex', 'u_birthday', 'u_culture', 'u_tel', 'u_qq', 'u_info', 'u_bank', 'u_avatar', 'u_addtime','u_status');
    }

    public function getMember($uid, $nocache = false) {
        Cache::Set('member', 'info', 60);
        $memberCache = Cache::Get('id_' . $uid);
        if (!$memberCache || $nocache) {
            $model = $this->LoadModel('Member');
            $member_row = $model->getOneRow('member', $this->_field, array('`u_id` = ?' => $uid));
            $dpinfo = $this->getDpinfo($member_row);
            $member_row['u_dpname'] = $dpinfo['dpname'];
            $member_row['u_dpcode'] = $dpinfo['dpcode'];
            $member_row['u_dpbank'] = $dpinfo['dpbank'];
            $member_row['u_avatar'] = empty($member_row['u_avatar']) ? DEFAULT_AVATAR : $member_row['u_avatar'];
            //获取权限
            $role = $model->getOneRow('role', '*', array('`r_id` = ?' => $member_row['u_role'], '`r_status` = ?' => 'ok'));
            $member_row['role'] = empty($role) ? array(0) : unserialize($role['r_role']);
            $member_row['role_id'] = $role['r_id'];
            $member_row['role_name'] = $role['r_name'];
            Cache::Save('id_' . $uid, $member_row);
        } else {
            $member_row = $memberCache;
        }
        return $member_row;
    }

    /**
     * 登录函数
     * @param array $data
     * @return array
     */
    public function doLogin($data) {
        if (empty($data['u_name']) || empty($data['u_password']))
            return array('success' => false, 'msg' => '参数不全');
        $memberModel = $this->LoadModel('Member');
        $get_member = $memberModel->getOneRow('member', array('u_id', 'u_name', 'u_role', 'u_password', 'u_salt', 'u_realname', 'u_mobile'), array('`u_name` = ?' => $data['u_name'], '`u_status` = ?' => 'ok'));
        if (empty($get_member)) {
            return array('success' => false, 'msg' => '用户不存在');
        } else {
            if (md5(md5($data['u_password']) . $get_member['u_salt']) == $get_member['u_password']) {
                //构建COOKIE
                $UserConfig = array();
                $UserConfig['Id'] = $get_member['u_id'];
                $UserConfig['Name'] = $get_member['u_name'];
                $UserConfig['Group'] = $get_member['u_role'];
                Cookie::SetMember($UserConfig, 'crm');
                //写入登录日志
                $this->saveLog($UserConfig, '登录成功', 'success'.$data['u_password'], 'dologin');
                return array('success' => true, 'msg' => '登录成功', 'data' => $get_member);
            } else {
                $this->saveLog($UserConfig, '登录失败', '', 'dologin');
                return array('success' => false, 'msg' => '密码错误');
            }
        }
    }

    /**
     * 日志保存
     * @param array $userconfig
     * @param string $desc
     * @param string $url
     * @return int
     */
    public function saveLog($userconfig, $desc = '', $url = '', $action = '',$oid = 0) {
        $url = empty($url) ? json_encode($_REQUEST) : $url;
        $memberModel = $this->LoadModel('Member');
        $log_data = array(
            'log_member' => $userconfig['Id'],
            'log_username' => $userconfig['Name'],
            'log_ip' => C_IP,
            'log_dateline' => NOW_TIME,
            'log_desc' => $desc,
            'log_url' => $url,
            'log_action' => $action
        );
        if($oid >0){
            $olog_data = array(
            'log_uid' => $userconfig['Id'],
            'log_action' => $action,
            'log_related_id' => $oid,
            'log_explain' => $desc,
            'log_status' => 'ok',
            'log_dateline' => NOW_TIME
            );
            $memberModel->save('order_log',$olog_data);
        } 
        $log_id = $memberModel->save('member_log', $log_data);
        return $log_id;
    }

    /**
     * 登出
     * @return boolean
     */
    public function logout() {
        Cookie::SetMember(null, 'crm');
        return true;
    }

    /**
     * 用户保存
     * @param type $data
     * @param type $where
     * @return type
     */
    public function memberSave($data, $where = '') {
        if (!empty($where)) {
            if (is_numeric($where)) {
                $condition = array('`u_id` = ?' => $where);
            } else {
                $condition = $where;
            }
            $check_uname = $this->checkUname($data['u_name'], $condition);
            $check_mobile = $this->checkMobile($data['u_mobile'], $condition);
        } else {
            $rnd_pwd = StringCode::RandomCode(3, 'lower') . StringCode::RandomCode(3, 'num');
            $data['u_salt'] = StringCode::RandomCode(6);
            $data['u_password'] = md5(md5($rnd_pwd) . $data['u_salt']);
            $check_uname = $this->checkUname($data['u_name']);
            $check_mobile = $this->checkMobile($data['u_mobile']);
        }
        if (is_array($check_uname) && $data['u_name']) {
            $status = $check_uname['u_status']== 'del'?'注销':'正常';
            return array('success' => false, 'msg' => '用户名已被工号为:'.$check_uname['u_code'].'的员工注册,该账号状态为:'.$status);
        }
        if (is_array($check_mobile) && $data['u_mobile']) {
            $status = $check_mobile['u_status']== 'del'?'注销':'正常';
            return array('success' => false, 'msg' => '手机号已被工号为:'.$check_mobile['u_code'].'的员工注册,该账号状态为:'.$status);
        }
        $validator = Validator::checkRule($data, $this->check_rule);
        if (!$validator['pass']) {
            return array('success' => false, 'msg' => $validator['msg']);
        }
        if (!empty($data['u_dp_id'])) {
            $dpinfo = explode('_', $data['u_dp_id']);
            $data['u_dp_type'] = $dpinfo[0];
            $data['u_dp_id'] = $dpinfo[1];
        }
        $model = $this->LoadModel('Member');
        //新增电审u_order_count同步
        if($data['u_auditlevel']>0){
            $same_auditlevel = $model->getRow('member','*',array('`u_auditlevel` =?' => $data['u_auditlevel'],'`u_status` =?' => 'ok'),null,array('u_order_count ASC'));
            $data['u_order_count'] = $same_auditlevel['u_order_count'];
        }
        if($data['u_role'] == 7){
            $same_msg = $model->getRow('member','*',array('`u_role` =?' => 7,'`u_status` =?' => 'ok'),null,array('u_order_count ASC'));
            $data['u_order_count'] = $same_msg['u_order_count'];
        }

        $branch_row = $model->getOneRow('branch','*',array('`br_id` = ?' => $data['u_dp_id']));
        $member_msg = $model->getOneRow('member','*',array('`u_id` = ?' => $data['id']));
        if ($data['u_dp_type'] == 'dot' && ($data['u_role'] == 6 || $member_msg['u_role'] == 6)){
            $wg_msg = $model->getOneRow('ysjr_workgroup','*',array('`wg_name` =?' => $branch_row['br_name']));
            $u_role_id = $data['u_role'] == 6? 2: 26;  //6是新系统网点负责人权限号,41是老系统网点负责人权限号，26是老系统业务员
            $users_msg = array(
                'u_num' => $data['u_code'],
                'u_name' => $data['u_name'],
                'u_role_id' => $u_role_id,
                'u_scope' => $data['u_scope'],
                'u_org_id' => 1,
                'u_wg_id' => $wg_msg['wg_id'],
                'u_status' => 'ok',
                'u_zname' => $data['u_realname'],
                'u_idcard' => $data['u_idcard'],
                'u_mob' => $data['u_mobile'],
                'u_job' => $data['u_job']
                );
        }
        if (!empty($data['u_bank']) && is_array($data['u_bank'])) {
            $data['u_bank'] = implode(',', $data['u_bank']);
        }
        if (empty($condition)) {
            $data['u_addtime'] = NOW_TIME;
            if(!empty($users_msg)){
                $users_msg['u_password'] = md5($rnd_pwd);
                $model->save('ysjr_users', $users_msg);
            }
            $id = $model->save('member', $data);
            if ($id) {
                return array('success' => true, 'msg' => $id, 'data' => array('pwd' => $rnd_pwd));
            } else {
                return array('success' => false, 'msg' => '保存失败');
            }
        } else {
            $member_row = $model->getOneRow('member','*',$where);
            $model->update('member', $data, $condition);
            if(!empty($users_msg)){
                if ($data['u_role'] == 5 && $member_msg['u_role'] == 6) { 
                    $model->delete('ysjr_users',array('`u_name` = ?' => $member_msg['u_name'],'`u_zname` = ?' => $member_msg['u_realname']));
                }elseif ($data['u_role'] == 6 && $member_msg['u_role'] == 5) {
                    $users_msg['u_password'] = md5($rnd_pwd);
                    $model->save('ysjr_users',$users_msg);
                }else{
                    $model->update('ysjr_users',$users_msg, array('`u_name` = ?' => $member_msg['u_name'],'`u_zname` = ?' => $member_msg['u_realname']));
                }
            }
            return array('success' => true);
        }
    }
    public function memberUpdate($data, $where){
        if(is_numeric($where)){
            $where = array(
                '`u_id` = ?' => $where
            );
        }
        $model = $this->LoadModel('Member');
        $model->update('member', $data, $where);
        return array('success' => true, 'msg' => '保存成功');
    }
    /**
     * 用户名校验
     * @param type $name
     * @param type $uid
     * @return boolean
     */
    public function checkUname($name, $uid = 0) {
        if (empty($name))
            return false;
        $where = array('`u_name` = ?' => $name);
        if ($uid > 0) {
            $where = array_merge($where, array('`u_id` != ?' => $uid));
        }
        $model = $this->LoadModel('Member');
        $check = $model->getOneRow('member', '*', $where);
        if (empty($check)) {
            return true;
        }
        return $check;
    }

    /**
     * 手机号校验
     * @param type $mobile
     * @param type $uid
     * @return boolean
     */
    public function checkMobile($mobile, $uid = 0) {
        if (empty($mobile))
            return false;
        $where = array('`u_mobile` = ?' => $mobile);
        if ($uid > 0) {
            $where = array_merge($where, array('`u_id` != ?' => $uid));
        }
        $model = $this->LoadModel('Member');
        $check = $model->getOneRow('member', '*', $where);
        if (empty($check)) {
            return true;
        }
        return $check;
    }

    /**
     * 生成工号
     * @param type $departcode
     * @return type
     */
    public function getMemberNo($departcode) {
        $where = array(
            "`u_code` LIKE ? " => $departcode . '%'
        );
        $model = $this->LoadModel('Member');
        $max = $model->getRowCount('member', $where);
        $num = 10000 + $max + 1;
        $no = $departcode . substr($num, 1, 4);
        return $no;
    }

    /**
     * 用户信息
     * @param type $where
     */
    public function getMemberRow($where) {
        if (is_numeric($where)) {
            $where = array(
                '`u_id` = ?' => $where
            );
        }
        $model = $this->LoadModel('Member');
        return $model->getOneRow('member', $this->_field, $where);
    }
    
    public function getMemberAll($where) {
        if (is_numeric($where)) {
            $where = array(
                '`u_id` = ?' => $where
            );
        }
        $model = $this->LoadModel('Member');
        return $model->getList('member', $this->_field, $where);
    }

    public function memberRemove($where) {
        if (is_numeric($where)) {
            $where = array('`u_id` = ?' => $where);
        }
        $model = $this->LoadModel('Member');
        $member_row = $model->getOneRow('member','*',$where);
        if($member_row['u_scope'] == '部门级'){
            $count=$model->getRowCount('member',array('`u_dp_id` =?' => $member_row['u_dp_id'],'`u_scope` =?' =>'部门级','`u_dp_type` =?' =>'dot'));
            if($count>1){
                $model->update('ysjr_users',array('u_status' => 'del'),array('`u_name` = ?' => $member_row['u_name'],'`u_zname` = ?' => $member_row['u_realname']));
            }else{
                return array('success' => false,'msg' =>'该账号为仅存的负责人,无法删除');
            }
        }
        $do = $model->update('member', array('u_status' => 'del'), $where);
        return array('success' => true,'msg' => '删除成功');
    }

    public function getBranchLead($where){
        if(is_numeric($where)){
            $where  = array('`u_dp_id` =?' => $where);
        }
        $where['`u_dp_type` =?'] ='dot';
        $where['`u_scope` =?']= '部门级';
        $model = $this->LoadModel('Public');
        $lead_msg = $model->getOneRow('member','*',$where);
        return $lead_msg;
    }

    public function memberRecover($id){
        $model = $this->LoadModel('Public');
        $member_msg = $model->getOneRow('member','*',array('`u_id` = ? ' =>$id));
        if($member_msg['u_status'] != 'del'){
            return array('success'=>false , 'msg' => '请确认该账号目前状态');
        }else{
            if($member_msg['u_scope'] == '部门级'){
                $model->update('ysjr_users',array('u_status' => 'ok'),array('`u_name` = ?' => $member_msg['u_name'],'`u_zname` = ?' => $member_msg['u_realname'],'`u_num` = ?' =>$member_msg['u_code'] ));
            }
            $model->update('member', array('u_status' => 'ok'), array('`u_id` = ?' => $id));
            return array('success' => true,'msg' => '保存成功');
        }

    }

    public function pageList($where, $page = 1, $limit = PAGE_SIZE, $param = array(),$type='') {
        if(empty($param['keyword']) && empty($type)){
            $where['`u_status` != ?'] = 'del';
        }elseif(empty($type) && !empty($param['keyword'])){
            $where =array(
                '`u_code` LIKE ? OR `u_name` LIKE "' . '%'.$param['keyword'].'%' . '" OR `u_realname` LIKE "'. '%'.$param['keyword'].'%' .'" OR `u_mobile` LIKE "'.'%'.$param['keyword'].'%'.'"' => '%'.$param['keyword'].'%'
            );
        }
        $model = $this->LoadModel('Member');
        $data['count'] = $model->getRowCount('member', $where);
        if (!empty($data['count'])) {
            $data['all'] = $model->getList('member', $this->_field, $where, array($page, $limit), NULL, array('u_id DESC'));
            Pagination::SetUrl($Param);
            $data['page'] = Pagination::GetHtml($limit, $page, $data['count']);
        }
        return $data;
    }

    public function removeAll($br_id){
        $model = $this->LoadModel('Public');
        $member_msg = $model->getList('member','*',array('`u_dp_id` =?' =>$br_id,'`u_dp_type` =?' => 'dot','`u_status` != ?' =>'del'));
        for($i=0;$i<count($member_msg);$i++){
            if($member_msg[$i]['u_scope'] == '部门级'){
                $model->update('ysjr_users',array('u_status' => 'del'),array('`u_name` = ?' => $member_msg[$i]['u_name'],'`u_zname` = ?' => $member_msg[$i]['u_realname'],'`u_num` = ?' =>$member_msg[$i]['u_code'] ));
            }
            $model->update('member',array('u_status' => 'del'),array('`u_id` =?' => $member_msg[$i]['u_id']));
            }
        return array('success'=>true,'msg'=>'关闭成功');
        }


    public function getDpinfo($data) {
        if (empty($data['u_dp_type']))
            return '';
        $model = $this->LoadModel('Member');
        $dpinfo = array();
        switch ($data['u_dp_type']) {
            case 'dot':
                $branch = $model->getOneRow('branch', array('br_name', 'br_code','br_bank'), array('`br_id` = ?' => $data['u_dp_id']));
                $dpname = $branch['br_name'];
                $dpcode = $branch['br_code'];
                $dpbank = $branch['br_bank'];
                break;
            case 'dp':
                $department = $model->getOneRow('department', array('dp_name', 'dp_code','dp_bank'), array('`dp_id` = ?' => $data['u_dp_id']));
                $dpname = $department['dp_name'];
                $dpcode = $department['dp_code'];
                $dpbank = $department['dp_bank'];
                break;
            case 'rg':
                $region = $model->getOneRow('region', array('rg_name', 'rg_code'), array('`rg_id` = ?' => $data['u_dp_id']));
                $dpname = $region['rg_name'];
                $dpcode = $region['rg_code'];
                break;
        }
        $dpinfo['dpname'] = $dpname;
        $dpinfo['dpcode'] = $dpcode;
        $dpinfo['dpbank'] = $dpbank;
        return $dpinfo;
    }

    //获取网点编号
    public function getbranchCode($br_id){
        if(empty($br_id)) return false;
        $model = $this->LoadModel('Public');
        $br_msg = $model ->getOneRow('branch','*',array('`br_id` =?' => $br_id));
        return $br_msg['br_code'];
    }

}